﻿using System;
using System.IO;
using System.Text;
using System.Xml.Serialization;
using System.Runtime.Serialization;

namespace GameEngine.Libs
{
    public class Serializer
    {
        public static Type GetType(string typeName)
        {
            var type = Type.GetType(typeName);
            if (type != null) return type;
            foreach (var a in AppDomain.CurrentDomain.GetAssemblies())
            {
                type = a.GetType(typeName);
                if (type != null)
                    return type;
            }
            return null;
        }

        public static string Serialize(object obj)
        {
            StringBuilder builder = new StringBuilder();
            XmlSerializer s = new XmlSerializer(obj.GetType());
            using (StringWriter writer = new StringWriter(builder))
            {
                s.Serialize(writer, obj);
            }
            return builder.ToString();
        }

        public static object DeSerialize(Type objType, string xml)
        {
            StringReader reader = new StringReader(xml);
            XmlSerializer deserializer = new XmlSerializer(objType);
            return deserializer.Deserialize(reader);

            //XmlSerializer deserializer = new XmlSerializer(obj.GetType());
            ////serializer.UnknownNode += new XmlNodeEventHandler(serializer_UnknownNode);
            ////serializer.UnknownAttribute += new XmlAttributeEventHandler(serializer_UnknownAttribute);

            //// A FileStream is needed to read the XML document.
            //FileStream fs = new FileStream(filename, FileMode.Open);
            ///* Use the Deserialize method to restore the object's state with
            //data from the XML document. */
            //return deserializer.Deserialize(fs);
        }
    }
}
